def print_with_bullets(lines, bullet='*'):
for line in lines:
print(f'{bullet} {line}')
NOTES
lines = [
'Hello.',
'Cosmo is the best mascot.',
'Python is pretty cool.'
]
print_with_bullets(lines)
print_with_bullets(lines, bullet='?')
def print_more_stuff(stuff='stuff', lines):
print(stuff)
print(lines)
NOTES
🐶 🐶 🐶
🐶 🐶 🐶
We have a grid of puppies. We'll use 'p' to indicate a puppy at a given position.
A puppy is happy if it is next to another puppy. "Next to" means there is another puppy up, down, left, right, or diagonal of the given puppy.
Write a function to return the coordinates (row, column) of all the happy puppies in a grid.
happy_puppies.py
¶NOTES
row
and column
, what is the coordinate of the position above? to the right? diagonal down-left?row
and column
are on the edge of the grid?[-1]
?if row - 1 >= 0 and grid[row - 1][column]...
def is_happy(grid, row, column):
if grid[row][column] != 'p':
return False
if row - 1 >= 0 and grid[row - 1][column] == 'p':
return True
if row + 1 < len(grid) and grid[row + 1][column] == 'p':
return True
if column - 1 >= 0 and grid[row][column - 1] == 'p':
return True
if column + 1 < len(grid[row]) and grid[row][column + 1] == 'p':
return True
if row - 1 >= 0 and column - 1 >= 0 and grid[row - 1][column - 1] == 'p':
return True
if row + 1 < len(grid) and column - 1 >= 0 and grid[row + 1][column - 1] == 'p':
return True
if row - 1 >= 0 and column + 1 < len(grid[row]) and grid[row - 1][column + 1] == 'p':
return True
if row + 1 < len(grid) and column + 1 < len(grid[row]) and grid[row + 1][column + 1] == 'p':
return True
return False
def find_happy(grid):
happy = []
for row in range(len(grid)):
for column in range(len(grid[row])):
if is_happy(grid, row, column):
happy.append((row, column))
return happy
grid = [
[None, 'p', 'p'],
['p', None, None],
[None, None, 'p']
]
find_happy(grid)
print_grid
¶...but better
def print_grid(grid):
for row in grid:
for item in row:
print(item, end=' ')
print()
fruits = [
['apple', 'pear', 'guava'],
['orange', 'banana', 'peach'],
['melon', 'mango', 'kiwi']
]
print_grid(fruits)
Write a function that prints a grid.
Each individual column should have a consistent width:
apple pear guava
orange banana peach
melon mango kiwi
pretty_print_grid.py
¶NOTES
str
a string?def pretty_print_grid(grid):
widths = []
for col in range(len(grid[0])):
col_width = None
for row in range(len(grid)):
item_width = len(str(grid[row][col]))
if col_width is None or item_width > col_width:
col_width = item_width
widths.append(col_width)
for row in grid:
for item, width in zip(row, widths):
print(item, end=' ' * (width - len(str(item)) + 1))
print()
fruits = [
['apple', 'pear', 'guava'],
['orange', 'banana', 'peach'],
['melon', 'mango', 'kiwi']
]
pretty_print_grid(fruits)
print()
hodge_podge = [
[1, 2, 3, 4, 5],
[50, 123, 4.32, None, 43.21],
['so','much','amaze',':)', True]
]
pretty_print_grid(hodge_podge)
grid_game
NOTES